package com.ys.controller.api.base;

import com.bo.annotation.Model;
import com.ys.config.MenuId;
import com.ys.entity.base.TbUserPersonalTaxCount;
import com.ys.entity.sys.YsCol;
import com.ys.service.base.TbUserPersonalTaxCountService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 员工个税统计表
 */
@Controller
@RequestMapping("/api/inter/tbUserPersonalTaxCount")
public class ApiInterTbUserPersonalTaxCountController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTbUserPersonalTaxCountController.class);

    @Autowired
    private CommonApiService<TbUserPersonalTaxCount> commonApiService;

    @Autowired
    private TbUserPersonalTaxCountService tbUserPersonalTaxCountService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TbUserPersonalTaxCount setSeachSql(TbUserPersonalTaxCount cond){

        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表
                .addField("(U.UserId + '/' + U.UserName) AS _ys_nameLinked")//工号/姓名

                .addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
                .addField("OI.OrgName AS deptName")//部门

                .addLeftJoin("THR_UserArchives UAS ON UAS.UserId = A.UserId")//用户档案表
                .addField("UAS.UserState AS userState");//员工状态

        cond.addLeftJoin("TB_UserPaySlip PS ON PS.Id = A.PaySlipId")//员工工资表
                .addField("PS.RealityPaySlip AS realityPaySlip");//实发工资

        cond.addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表
                .addField("O.OrgName AS orgName");//所属公司

        cond.addLeftJoin("TB_UserMonthPerformance MP ON MP.Id = PS.MonthPerformanceId")//员工月度绩效信息表
                .addField("MP.Rank AS rank")//岗位职级
                .addField("MP.Type AS type");//岗位工种(0总经理 1副总经理 2责任月薪型员工 3绩效提奖型员工 4研发人员)

        cond.addLeftJoin("TB_UserPersonalTaxCount AP ON AP.UserId = A.UserId AND AP.CountMonth = A.CountMonthBefore AND AP.OrgId = A.OrgId")//员工个税统计表上个月
                .addField("ISNULL(AP.IncomeAddup,0) AS incomeAddupBefore")//上个月收入累计
                .addField("ISNULL(AP.DeductCostAddup,0) AS deductCostAddupBefore")//上个月扣除费用累计
                .addField("ISNULL(AP.SpecialDeductCostAddup,0) AS specialDeductCostAddupBefore")//上个月专项扣除累计
                .addField("ISNULL(AP.OtherDeductCostAddup,0) AS otherDeductCostAddupBefore")//上个月其他扣除
                .addField("ISNULL(AP.SpecialAddDeductCostAddup,0) AS specialAddDeductCostAddupBefore");//上个月专项附加扣除



        //排序
        cond.setOrderby("A.CountMonth DESC,A.UserId ASC");
        //权限
        cond = commonApiService.dataAuth(MenuId.TB_UserPersonalTaxCount, cond);
        return cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tbUserPersonalTaxCount:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TbUserPersonalTaxCount cond,String conditions
    ){
        try {
            System.out.println("conditions"+conditions);
            cond = setSeachSql(cond);
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_nameLinked");//工号/姓名
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TbUserPersonalTaxCount cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TB_UserPersonalTaxCount)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TbUserPersonalTaxCount> util = new ExportExcelUtils<>(new TbUserPersonalTaxCount());
            String toFilePath = util.exportExcel(listData, listField, "员工个税统计表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/toDel")
    @ResponseBody
    public R toDel(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            int count = 0;
            //删除
            for (int i = 0; i < idList.size(); i++) {
                R res= tbUserPersonalTaxCountService.toDel(Long.parseLong(idList.get(i)));
                if(res.getCode()==0){
                    count ++;
                }
            }
            String backMsg = "成功删除"+count+"条！";
            if(idList.size()!=count){
                backMsg+="（工资条中的工资状态为“个税已导入”才可删除）";
            }
            return R.ok(backMsg);
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



}